package com.kehongborui.fliggy.interceptor;

import com.kehongborui.fliggy.entity.RoleModule;
import com.kehongborui.fliggy.entity.User;
import com.kehongborui.fliggy.enums.ModuleEnum;
import com.kehongborui.fliggy.service.ModuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.List;

import static com.kehongborui.fliggy.enums.LOGIN_USER.MODULE_LIST;
import static com.kehongborui.fliggy.enums.LOGIN_USER.USER;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-08-30
 */
public class AuthenticationInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private ModuleService moduleService;


//    private Map<Integer, List> power = new HashMap<>();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取当前模块
        Integer currentModule = (Integer)request.getSession().getAttribute(ModuleEnum.CURRENT_MODULE.name());
        // 获取登录用户信息
        User loginUser = (User) request.getSession().getAttribute(USER.name());
        Object moduleObject=  request.getSession().getAttribute(MODULE_LIST.name());
        if (loginUser == null && moduleObject == null) {
            // 游客模块
            int visitor = 4;
            moduleObject = moduleService.findByRoleId(visitor);
            request.getSession().setAttribute(MODULE_LIST.name(), moduleObject);
        }

        // 判断是否有权限
        for (RoleModule rm : (List<RoleModule>)moduleObject) {
            // 如果当前模块在当前用户所有有的权限模块当中，则进入到下一拦截器（放行）
            if (rm.getModuleId() == currentModule) {
                return true;
            }
        }

        response.sendRedirect("/nopower");
        return false;
    }
}
